//
//  TaoboProdcutDetailViewController.swift
//  viewcontroller_test
//
//  Created by 曾思宇 on 16/4/2.
//  Copyright © 2016年 海南开工信息技术有限公司. All rights reserved.
//

import UIKit

class TaoboProdcutDetailViewController: UIViewController, UIScrollViewDelegate, UITableViewDelegate, UITableViewDataSource {

    @IBOutlet weak var scrollView: UIScrollView!
    
    
    @IBAction func onClickDoSomething(sender: AnyObject) {
        
        NSLog("\(scrollView.contentSize)")
        NSLog("\(scrollView.contentOffset)")
        NSLog("\(scrollView.contentInset)")
        
        UIView.animateWithDuration(0.3, animations: {
            self.scrollView.contentSize.height = 800
        }){ _ in
            
            self.scrollView.scrollEnabled = true
            
        }
        
        
    }
    
    
    
    var view_top: UITableView?
    var view_bottom: UIView?
    var view_Indicator: UILabel?
    
    
    var productPicturesTableViewCell: TableViewCellPictures?
    var productProfileTableViewCell: TableViewCellProfile?
    var storeProfileTableViewCell: TableViewCellStoreProfile?
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // Do any additional setup after loading the view.
        
        // 设置最顶部的 TableView
        view_top = UITableView(frame: CGRect(x: 0, y: 0, width: view.bounds.width, height: 800), style: UITableViewStyle.Grouped)
        view_top?.autoresizingMask = .FlexibleWidth
        scrollView.addSubview(view_top!)
        
        
        
        view_top?.delegate = self
        view_top?.dataSource = self
        
        
        
        view_top?.registerNib(UINib(nibName: "TableViewCellPictures", bundle: nil), forCellReuseIdentifier: "pictures")
        productPicturesTableViewCell = view_top?.dequeueReusableCellWithIdentifier("pictures") as? TableViewCellPictures
        productPicturesTableViewCell?.imagesView.addImage(UIImage(named: "product_1")!)
        productPicturesTableViewCell?.imagesView.addImage(UIImage(named: "product_2")!)
        productPicturesTableViewCell?.imagesView.addImage(UIImage(named: "product_3")!)
        
        view_top?.registerNib(UINib(nibName: "TableViewCellProfile", bundle: nil), forCellReuseIdentifier: "profile")
        productProfileTableViewCell = view_top?.dequeueReusableCellWithIdentifier("profile") as? TableViewCellProfile
        
        view_top?.registerNib(UINib(nibName: "TableViewCellStoreProfile", bundle: nil), forCellReuseIdentifier: "store_profile")
        storeProfileTableViewCell = view_top?.dequeueReusableCellWithIdentifier("store_profile") as? TableViewCellStoreProfile
        
        view_top?.allowsSelection = false
        view_top?.tableHeaderView = UIView(frame: CGRect(x: 0, y: 0, width: view.bounds.width, height: 0.1))
        
        
        view_Indicator = UILabel(frame: CGRect(x: 0, y: 800, width: view.bounds.width, height: 40))
        view_Indicator?.text = "继续拖动，查看图文详情"
        view_Indicator?.font = UIFont.systemFontOfSize(11)
        view_Indicator?.textAlignment = .Center
        scrollView.addSubview(view_Indicator!)
        
        view_bottom = UIView(frame: CGRect(x: 0, y: 840, width: view.bounds.width, height: 800))
        view_bottom!.backgroundColor = UIColor.darkGrayColor()
        scrollView.addSubview(view_bottom!)
        
        
        scrollView.contentSize = CGSize(width: 320, height: 840)
        
        scrollView.delegate = self
        
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    override func willMoveToParentViewController(parent: UIViewController?) {
        
        if let navController = parent as? UINavigationController {
            navController.navigationBarHidden = false
        }
    }
    
    
    override func viewWillAppear(animated: Bool) {
        
        navigationController?.navigationBarHidden = false
    }
    
    
    // helper function to calculate how far we can scroll
    func calcScrollRange() -> CGFloat {
        
        let delta = scrollView.contentSize.height - (scrollView.frame.height - scrollView.contentInset.top - scrollView.contentInset.bottom)
        
        return max(0.0, delta)
    }
    
    
    var canTransition = false
    var transiting = false
    
    func scrollViewDidScroll(scrollView: UIScrollView) {
        //NSLog("scrollView did scroll(contentOffset):\(scrollView.contentOffset)")
        
        let scrollRange = calcScrollRange()
        
        let delta = scrollView.contentOffset.y - scrollView.contentInset.top - scrollRange
        
        //NSLog("dragging:\(scrollView.dragging), tracking:\(scrollView.tracking), decelart:\(scrollView.decelerating)")
        
        if transiting {
            
            NSLog("Transiting")
            
        }
        else {
            
            
            if canTransition && scrollView.decelerating {
                
                beginTransition()
            }
                
                
            else if delta > 100.0 && !scrollView.decelerating {
                
                view_Indicator!.text = "释放拖动，查看图文详情"
                
                canTransition = true
                NSLog("can")
                
            }
            else {
                view_Indicator?.text = "继续拖动，查看图文详情"
                canTransition = false
            }
        }
    }
    
    func beginTransition() {
        transiting = true
        
        scrollView.scrollEnabled = false
        scrollView.contentSize = CGSize(width: 320, height: 1640)
        
        
        
        UIView.animateWithDuration(0.3, animations: {
            self.scrollView.contentOffset.y = 840
        }) { (_) in
            self.endTransition()
        }
        
        
    }
    
    func endTransition() {
        
        transiting = false
        canTransition = false
    }
    
    /*========================================================================================================
     
     监测 TableView 的contentSize变化
     
     ========================================================================================================*/
    
    
    
    /*========================================================================================================
     
     UITableView's delegate and datasource implementation
 
     ========================================================================================================*/
    
    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 2
    }
    
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        if section == 0 {
            return 2
        }
        else if section == 1 {
            return 1
        }
        
        return 2
    }
    
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        
        if indexPath.section == 0 && indexPath.row == 0 {
            return productPicturesTableViewCell!
        }
        else if indexPath.section == 0 && indexPath.row == 1 {
            return productProfileTableViewCell!
        }
        else if indexPath.section == 1 && indexPath.row == 0 {
            return storeProfileTableViewCell!
        }
        
        return productPicturesTableViewCell!
    }
    
    func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        
        if indexPath.section == 0 && indexPath.row == 0 {
            let size = productPicturesTableViewCell?.sizeThatFits(CGSizeZero)
            return (size?.height)!
        }
        else if indexPath.section == 0 && indexPath.row == 1 {
            
            let size = productProfileTableViewCell?.sizeThatFits(CGSizeZero)
            
            return (size?.height)!
            
        }
        else if indexPath.section == 1 && indexPath.row == 0 {
            let size = storeProfileTableViewCell?.sizeThatFits(CGSizeZero)
            return (size?.height)!
        }
        
        
        
        return 45
        
    }
    
    func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 4
    }
    
    func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        
        if section == 1 {
            return 4
        }
        return 0
    }
    
    

}
